/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-16 17:17:03
 * @filename : controller/subsubtotal_profile.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){

    var name = 'Subtotal Profile', mId = 'subtotal_profile',    
        highchartMC = require('{model}highchart'), 
        highcharts = require('highcharts'),
        tpl = require('{view}page_gold.tpl'),
        tplH = require('{view}head_gold.tpl'),
        tplT = require('{view}table.tpl'),
        tplS = require('{view}select.tpl');
      
    var highchartM = new highchartMC.highchartM;

    var tempOpt = {
             engine : '',
             begin_date : null,
             end_date : null,
             group : 'day'
        };
 
    var SubtotalProfileView = Backbone.View.extend({
    
        initialize: function (obj) { 
            this.run(obj);
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                $('#'+mId).find('.m_head').append(_.template(tplH));
                this.defaultOpt();
                this.afterBindEvt();
                this.fetchData(tempOpt); 
            } else {
                $('#'+mId).css('display','block');
            }
 
        },

        afterBindEvt : function() {
             var tthis = this,dom = $('#'+mId);
             
             new Pikaday({
                    field: dom.find('.from_time')[0],
                    firstDay: 1,
                    minDate: new Date('1997-01-01'),
                    maxDate: new Date('2020-12-31'),
                    yearRange: [1997,2020]
             });
             
             new Pikaday({
                    field: dom.find('.to_time')[0],
                    firstDay: 1,
                    minDate: new Date('1997-01-01'),
                    maxDate: new Date('2020-12-31'),
                    yearRange: [1997,2020]
             });

            dom.find('.selectTime').on('change',function(){
                var val = $(this).val();
                    share.setInputDate(val,mId);
            });
            /*
            dom.find('.selectInfo').on('change',function(){
                var val = $(this).find('select').val();
                share.cacheSelect(val);
            });
            */
            dom.find('.do').on('click',function(){
                var bool = share.getPostData(tempOpt,mId); 
                if (bool) { 
                    tthis.fetchData(tempOpt);
                }
            });

            dom.find('.m_head').find('input[type="text"]').on('focus',function(){
                $('#'+mId).find('.selectTime').find("option[value='']").attr("selected",true); 
            });

        },
     
        defaultOpt : function() {
             var dom = $('#'+mId);
             this.selectSite();
             share.setInputDate('last-week',mId);
             tempOpt.end_date = dom.find('.to_time').val();
             tempOpt.begin_date = dom.find('.from_time').val(); 
             tempOpt.group  = 'day';
             tempOpt.engine = dom.find('.selectInfo').find('select').val();
             if (tempOpt.engine == '0') { tempOpt.engine = ''};
        },

        selectSite : function() {
             var siteInfo =  share.getAllSites(1);
             $('#'+mId).find('.selectInfo').html(_.template(tplS)({obj:siteInfo}));
        },  

        fetchData : function(data) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+'total_gold',
                type : 'POST',
                data : data,
                success : function(data) {
                    //console.log(data);
                    tthis.fetchSuccess(data);
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };
           
            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt,true);
        },

        fetchSuccess : function(data) {
            
            _.each(data,function(obj) {
                obj.IOS_PROFILE = obj.IOS_PROFILE;
                obj.MAIN_PROFILE = Number(obj.TOTAL_PROFILE) - Number(obj.APP_PROFILE) - Number(obj.MOBILE_PROFILE);
            });

            this.details(data);
            this.changeHighChartM(data);  
        },

        details : function(data) {
            var arr = [];
                arr.push({name:'Date',val:'FMT_DATE',title:'Date'});
                arr.push({name:'Total',val:'TOTAL_PROFILE',title:'Total'});
                arr.push({name:'PC',val:'MAIN_PROFILE',title:'Users registered via pc'});
                arr.push({name:'Mobile',val:'MOBILE_PROFILE',title:'Users registered via mobile'});
                arr.push({name:'IOS',val:'IOS_PROFILE',title:'Users registered via iOS app'});
                arr.push({name:'Android',val:'ANDROID_PROFILE',title:'Users registered via Android app'});

            data = _.clone(data).reverse();
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data,arr:arr}));
        },

        changeHighChartM : function(arr) {
               
            var xAxis = highchartM.get('xAxis'),
                yAxis = highchartM.get('yAxis'),
                tooltip = highchartM.get('tooltip');
                series = highchartM.get('series'),
                chart = highchartM.get('chart'),
                title = highchartM.get('title'),
                plotOptions = highchartM.get('plotOptions');

                title = {text : 'subtotal Profile'}; 
                chart = {type : 'column',width:$('#index_right').width()}; 
                xAxis = {categories : _.pluck(arr,'DATE')}; 
                yAxis = {};
                tooltip = {shared:true};

                series = [{
                            name: 'Mobile Profile',
                            data: _.map(_.pluck(arr,'MOBILE_PROFILE'),function(num){return Number(num)})
                        }, {
                            name: 'Android Profile',
                            data: _.map(_.pluck(arr,'ANDROID_PROFILE'),function(num){return Number(num)})
                        },{
                            name: 'IOS Profile',
                            data: _.map(_.pluck(arr,'IOS_PROFILE'),function(num){return Number(num)})
                        }, {
                            name: 'Main Profile',
                            data: _.map(_.pluck(arr,'MAIN_PROFILE'),function(num){return Number(num)})
                }];

                plotOptions.column = {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: arr.length < share.dataLabelNum ? true : false,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                    }
                };

                highchartM.set('tooltip',tooltip);
                highchartM.set('plotOptions',plotOptions); 
                highchartM.set('title',title); 
                highchartM.set('xAxis',xAxis); 
                highchartM.set('series',series);
                highchartM.set('chart',chart);
                this.renderHighChart();     
        }, 

        renderHighChart : function() {
              var height = share.getGraphHeight(tempOpt); 
             $('#'+mId+'_graph').height(height+'px').highcharts(highchartM.attributes);
        }

    });
	module.exports = SubtotalProfileView;
});



